package com.deepglint.wc;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @author mj
 * @version 1.0
 * @date 2021-11-05 23:18
 */

// 批处理word count
public class WorkCount {
    public static void main(String[] args) throws Exception{
        // 创建执行环境
        ExecutionEnvironment environment = ExecutionEnvironment.getExecutionEnvironment();

        // 从文件读取数据
        String inputPath = "C:\\Users\\马军\\Desktop\\Idea-workspace\\flink\\src\\main\\resources\\hello.txt";

        DataSet<String> inputDataSet = environment.readTextFile(inputPath);

        // 对数据集进行处理，按空格分词展开(word,1)二元组进行统计
        DataSet<Tuple2<String, Integer>> resultSet = inputDataSet.flatMap(new MyFlatMap())
                .groupBy(0) // 按照第一个位置的word分组flink-streaming-java
                .sum(1)// 将第二个位置上的数据求和
                .setParallelism(1); // 设置sum阶段的并行度

        resultSet.print();
    }

    // 自定义类，实现FlatMapFunction接口
    public static class MyFlatMap implements FlatMapFunction<String, Tuple2<String, Integer>> {

        @Override
        public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
            // 按空格分词
            String[] words = value.split(" ");

            //遍历所有的words，包成二元组输出
            for (String word : words) {
                out.collect(new Tuple2<>(word, 1));
            }
        }
    }
}
